package com.compunit.composite.core;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;

import com.compunit.composite.core.interfaces.IExporter;

/**
 * <code>AbstractExporter</code> defines the abstraction
 * of an utility exporter unit. It provides the basic
 * functionality for creating the destination file using
 * given directory and file name information. Subclasses
 * should provide the detailed export logic.
 *
 * @author Yi Wang (Neakor)
 * @version Creation date: 11-12-2009 19:32 EST
 * @version Modified date: 12-05-2009 13:58 EST
 */
public abstract class AbstractExporter implements IExporter {

	@Override
	public void export(final URL dir, final String filename) throws URISyntaxException, IOException {
		if(this.isEmpty()) return;
		// Form URL.
		String raw = dir.getPath();
		if(!raw.endsWith("/")) raw += "/";
		final String path = raw.substring(raw.indexOf("/"), raw.length());
		// Export.
		this.export(path, filename);
	}
	
	@Override
	public void export(final String dir, final String filename) throws URISyntaxException, IOException {
		if(this.isEmpty()) return;
		final String path = dir + filename;
		// Create new file.
		final File file = new File(path);
		if(file.exists()) file.delete();
		file.createNewFile();
		// Do export logic.
		this.doExport(file);
	}

	/**
	 * Perform the detailed export logic.
	 * @param destination The destination <code>File</code>.
	 * @throws URISyntaxException If URL handling failed. 
	 * @throws IOException If file handling failed.
	 */
	protected abstract void doExport(final File destination) throws URISyntaxException, IOException;
}
